<!-- rightColumnActionsRenderer.vue -->
<script>
import { defineComponent, ref, watch } from 'vue'

import { Switch } from 'ant-design-vue'

export default defineComponent({
  name: 'SwitchRenderer',
  components: {
    Switch,
  },
  props: {
    params: {
      type: Object,
      required: true,
    },
  },
  setup(props, { expose }) {
    const value = ref(props.params.value)

    // 监听props.params.value的变化，确保组件状态与外部数据同步
    watch(
      () => props.params.value,
      (newVal) => {
        console.log('监听', newVal)
        value.value = newVal
      },
    )

    const getValue = () => {
      return value.value
    }

    const onChange = (val) => {
      value.value = val
      // 安全检查
      if (props.params && props.params.api && props.params.colDef && props.params.colDef.field && props.params.node) {
        // 使用AG Grid的setDataValue方法更新数据，确保触发cellValueChanged事件
        props.params.node.setDataValue(props.params.colDef.field, val)
      }
    }

    expose({
      getValue,
    })

    return {
      value,
      onChange,
    }
  },
})
</script>

<template>
  <div style="width: 100%; height: 100%; display: flex; justify-content: center; align-items: center">
    <Switch v-model:checked="value" @change="onChange" />
  </div>
</template>
